<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>


        // 参数很多 ， 必须按照顺序传参
        // data ???   'username:yy&userpwd:123'


        ajax({
            type : 'post' ,
            url : '../php/post.php' ,
            data : {
                username : 'yy' ,
                userpwd : '123'
            } ,
            cb : data => {
                console.log(data);
            }
        })



        function ajax(options) {

            const {
                type ,
                data = {} ,
                url ,
                cb
            } = options ;

            // {username:'yy' , userpwd : 123}    =>   username=yy&userpwd=123
            let str = '' ;
            // 遍历data
            for(let key in data) {
                str += `${key}=${data[key]}&` ;
            }
            str = str.substring(0,str.length-1) ;
            console.log(str);


            const xhr = new XMLHttpRequest();
            if (type === 'get') {
                xhr.open(type, url + '?' + str , true);
                xhr.send();
            } else {
                xhr.open('post' , url , true) ;
                // 设置一个请求头  --- 定义数据格式
                xhr.setRequestHeader('content-type' , 'application/x-www-form-urlencoded');
                xhr.send(str) ;
            }


            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    let data = xhr.responseText;
                    data = JSON.parse(data);
                    cb(data);
                }
            }
        }

    </script>

</body>

</html>